package com.hancher.common.base;

import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewbinding.ViewBinding;

import com.hancher.common.androidutil.LogUtil;
import com.hancher.common.androidutil.StateBarUtil;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;


/**
 * 作者 : Hancher ytu_shaoweijie@163.com <br/>
 * 时间 : 2021/8/25 0025 0:01 <br/>
 * 描述 :
 */
public abstract class BaseActivity<B extends ViewBinding> extends AppCompatActivity {

    protected B binding;

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        LogUtil.map2Json("全埋点(按键):", "event", KeyEvent.keyCodeToString(event.getKeyCode()),
                "code", event.getKeyCode(), "action", actionToString(event.getAction()));
        return super.dispatchKeyEvent(event);
    }

    public static String actionToString(int action) {
        switch (action) {
            case KeyEvent.ACTION_DOWN:
                return "ACTION_DOWN";
            case KeyEvent.ACTION_UP:
                return "ACTION_UP  ";
            case KeyEvent.ACTION_MULTIPLE:
                return "ACTION_MULTIPLE";
            default:
                return Integer.toString(action);
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        setStateBar();
        super.onCreate(savedInstanceState);

        //bing 反射 200ms
        try {
            Type superclass = getClass().getGenericSuperclass();
            Class<B> aClass = (Class<B>) ((ParameterizedType) superclass).getActualTypeArguments()[0];
            Method method = aClass.getDeclaredMethod("inflate", LayoutInflater.class);
            binding = (B) method.invoke(null, getLayoutInflater());
            setContentView(binding.getRoot());
        } catch (InvocationTargetException e) {
            LogUtil.e(e.getTargetException());
        } catch (Exception e) {
            LogUtil.e(e);
        }

        initView();
        initListener();
        initData();
    }

    /**
     * 可以覆写，修改单个界面的状态栏颜色
     */
    public void setStateBar() {
        StateBarUtil.white(this);
    }

    protected void initData() {

    }

    protected void initListener() {

    }

    protected void initView() {

    }

    @Override
    protected void onDestroy() {
        binding = null;
        super.onDestroy();
    }
}
